const db = require('../config/db')

// 定义领养宠物类
class Pet {
    // 添加领养宠物
    // age, localstation（地址）, myname（联系人）,myphone（联系电话）,petcategory（分类）
    // ,petimg（图片）,petinsectnum（已绝育）,petname,petsterilizationnum(已驱虫),petstory,
    // petvaccinumnum（已疫苗）,petwhich（品种）,sex,timehs（21:52）,timeymd（2024-01-01）,user_id（发布者）

    // 参数：
    // age, localstation, myname,myphone,petcategory,petimg,petinsectnum,petname,petsterilizationnum,petstory,petvaccinumnum,petwhich,sex,timehs,timeymd,user_id
    add(age, localstation, myname, myphone, petcategory, petimg, petinsectnum, petname, petsterilizationnum, petstory, petvaccinumnum, petwhich, sex, timehs, timeymd, user_id) {
        return new Promise((resolve, reject) => {
            let date = new Date();
            let pet_create_time = date.toLocaleDateString() + " " + (date.toLocaleTimeString());

            // 添加领养宠物
            let sql = `insert into db_pet(age, localstation, myname,myphone,petcategory,petimg,petinsectnum,petname,petsterilizationnum,petstory,petvaccinumnum,petwhich,sex,timehs,timeymd,user_id,pet_create_time) 
          values('${age}','${localstation}','${myname}','${myphone}','${petcategory}','${petimg}','${petinsectnum}','${petname}','${petsterilizationnum}','${petstory}','${petvaccinumnum}','${petwhich}','${sex}','${timehs}','${timeymd}','${user_id}','${pet_create_time}')`;
            db.query(sql)
                .then(
                    content => {
                        console.log('-->', content)
                        resolve({
                            code: 200,
                            msg: "发布领养宠物成功。",
                            content
                        })
                    },
                    err => {
                        console.log('-->', err)
                        reject({
                            code: 500,
                            msg: "发布领养宠物失败。",
                            err
                        })
                    }
                )
        })
    }

    // 删除发布送养宠物记录
    remove(id) {
        return new Promise((resolve, reject) => {
            db.query(`select * from db_pet where id = '${id}'`)
                .then(
                    rows => {
                        if (rows && rows.length === 1) {
                            // 存在
                            let sql = `delete from db_pet where id = '${id}'`
                            db.query(sql)
                                .then(
                                    content => {
                                        resolve({
                                            code: 200,
                                            msg: "删除领养宠物记录成功",
                                            content
                                        })
                                    },
                                    err => {
                                        reject({
                                            code: 500,
                                            msg: "删除领养宠物记录失败",
                                            err
                                        })
                                    }
                                )
                        }
                        else {
                            // 不存在
                            resolve({
                                code: 404,
                                msg: "不存在这个领养宠物"
                            })
                        }
                    },
                    err => {
                        reject({
                            code: 500,
                            msg: "查询领养宠物数据失败",
                            err
                        })
                    }
                )
        })
    }

    // 获取发布的送养宠物列表（分页）
    async list(page, pageSize) {
        // 获取用户总数
        let total;
        await this.total().then(
            content => {
                total = content.result[0].total
            }
        )
        return new Promise((resolve, reject) => {
            //获取分页数据
            let page_num = ((parseInt(page) - 1) * parseInt(pageSize))
            let page_size = (parseInt(pageSize))
            let sql = `select * from db_pet limit ${page_num} , ${page_size}`
            db.query(sql)
                .then(
                    result => {
                        resolve({
                            code: 200,
                            total,
                            msg: "获取领养宠物列表成功。",
                            result
                        })
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: "获取领养宠物列表失败",
                            err
                        })
                    }
                )

        })
    }

    // 统计领养宠物记录总数量
    total() {
        return new Promise((resolve, reject) => {
            let sql = 'select count(*) as total from db_pet';
            db.query(sql)
                .then(
                    result => {
                        resolve({
                            code: 200,
                            msg: "统计数据成功。",
                            result
                        })
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: "统计信息失败",
                            err
                        })
                    }
                )
        })
    }

    // 获取详情
    detail(id) {
        return new Promise((resolve, reject) => {
            db.query(`select * from db_pet where id = '${id}'`)
                .then(
                    rows => {
                        if (rows && rows.length === 1) {
                            // 存在
                            resolve({
                                code: 200,
                                msg: "获取宠物详情成功",
                                result: rows[0]
                            })
                        }
                        else {
                            // 不存在
                            resolve({
                                code: 404,
                                msg: "不存在这个领养宠物"
                            })
                        }
                    },
                    err => {
                        reject({
                            code: 500,
                            msg: "查询领养宠物数据失败",
                            err
                        })
                    }
                )
        })
    }

    // 获取发布的送养宠物列表（分页）
    async list_classify(page, pageSize,petcategory) {
        // 获取总数
        return new Promise((resolve, reject) => {
            //获取分页数据
            let page_num = ((parseInt(page) - 1) * parseInt(pageSize))
            let page_size = (parseInt(pageSize))
            console.log(page, pageSize,petcategory)
            // let sql = petcategory == undefined ? `select * from db_pet limit ${page_num} , ${page_size}`:`select * from db_pet where petcategory = '${petcategory}' limit ${page_num} , ${page_size}`
            let sql = ''
            if(petcategory == undefined || petcategory ==''){
                sql = `select * from db_pet limit ${page_num} , ${page_size}`
            }
            else {
                sql = `select * from db_pet where petcategory = '${petcategory}' limit ${page_num} , ${page_size}`
            }
            db.query(sql)
                .then(
                    result => {
                        // console.log(result)
                        resolve({
                            code: 200,
                            msg: "获取分类列表成功。",
                            result
                        })
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: "获取分类列表失败",
                            err
                        })
                    }
                )

        })
    }

    // 搜索宠物（分类名称，昵称，种类）
    search(keyword) {
    return new Promise((resolve, reject) => {
        let sql = `select * from db_pet where petcategory like '%${keyword}%' or petname like '%${keyword}%' or petwhich like '%${keyword}%'`;
        db.query(sql)
            .then(
                (rows) => {
                    resolve({
                        code: 200,
                        msg: `关键字“${keyword}”搜索的结果`,
                        result: rows
                    })
                },
                (err) => {
                    reject({
                        code: -1,
                        msg: '关键字搜索失败。'
                    })
                },
            )
    })
}
}
module.exports = new Pet();